package com.x.gzip;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GZIPUtils
{
	
	private static final Logger logger = LoggerFactory.getLogger(GZIPUtils.class);
	
	public static final String GZIP_ENCODE_UTF_8 = "UTF-8";
	
	private GZIPUtils()
	{
	}
	
	public static byte[] compress(String str, String encoding) throws Exception
	{
		if (str == null || str.length() == 0)
		{
			return null;
		}
		try
		{
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			GZIPOutputStream gzip = new GZIPOutputStream(out);
			gzip.write(str.getBytes(encoding));
			gzip.finish();
			gzip.close();
			return out.toByteArray();
		}
		catch (Exception e)
		{
			logger.error(str + "", e);
			throw new Exception();
		}
	}
	
	public static byte[] compress(String str) throws Exception
	{
		return compress(str, GZIP_ENCODE_UTF_8);
	}
	
	public static byte[] uncompress(byte[] bytes)
	{
		if (bytes == null || bytes.length == 0)
		{
			return null;
		}
		ByteArrayOutputStream out = null;
		ByteArrayInputStream in = null;
		GZIPInputStream ungzip = null;
		try
		{
			out = new ByteArrayOutputStream();
			in = new ByteArrayInputStream(bytes);
			ungzip = new GZIPInputStream(in);
			byte[] buffer = new byte[1024];
			int n;
			while ((n = ungzip.read(buffer)) >= 0)
			{
				out.write(buffer, 0, n);
			}
			return out.toByteArray();
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
		finally
		{
			try
			{
				if (ungzip != null)
				{
					ungzip.close();
				}
				if (out != null)
				{
					out.close();
				}
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}
	
	public static String uncompressToString(byte[] bytes, String encoding) throws Exception
	{
		if (bytes == null || bytes.length == 0)
		{
			return null;
		}
		ByteArrayOutputStream out = null;
		ByteArrayInputStream in = null;
		GZIPInputStream ungzip = null;
		try
		{
			out = new ByteArrayOutputStream();
			in = new ByteArrayInputStream(bytes);
			ungzip = new GZIPInputStream(in);
			byte[] buffer = new byte[1024];
			int n;
			while ((n = ungzip.read(buffer)) >= 0)
			{
				out.write(buffer, 0, n);
			}
			return out.toString(encoding);
		}
		catch (Exception e)
		{
			throw new Exception();
		}
		finally
		{
			try
			{
				if (ungzip != null)
				{
					ungzip.close();
				}
				if (out != null)
				{
					out.close();
				}
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}
	
	public static String uncompressToString(byte[] bytes) throws Exception
	{
		return uncompressToString(bytes, GZIP_ENCODE_UTF_8);
	}
}